// pages/shoppingCar/shoppingCar.js
var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasGoods: false,
    cart_list: [],
    cart: {
      num: 0,
      cart_count: 0,
    },
    all_check: 0,
    check_list: [],
    goods_num: '' //商品数量
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      // wx.switchTab({
      //   url: '../me/me'
      // })
      return;
    }

    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }
    console.log("check_list", check_list);
    that.setData({
      check_list: check_list,
    })
    that.initData();
  },
  initData: function() {
    var that = this;
    var check_list = that.data.check_list;

    var s_num = 0; //选中的价格总和
    var s_count = 0; //选中的总数量
    if (wx.getStorageSync('token') == '') {
      var temp = wx.getStorageSync('temp_goods');
      console.log(temp);
      that.data.cart_list = temp;
      that.initCheck();
    } else {
      util.postUrl('cart/get_list', {

      }, function(res) {
        if (res.data.code == 200) {
          var temp = res.data.datas.cart_list;
          for (var shop of temp) {
            shop.fee = shop.store_free_price - shop.store_total_price;
          }
          that.data.cart_list = temp;
          that.initCheck();
        }


      })
    }
    that.initRed();
  },
  initCheck: function() {
    var that = this;
    var check_list = that.data.check_list;
    that.setData({
      check_list: check_list,
    })
    wx.setStorageSync('check_list', check_list);
    var s_num = 0; //选中的价格总和
    var s_count = 0; //选中的总数量
    var l = 0; //商品大少
    var temp = that.data.cart_list;


    for (var shop of temp) {
      l = l + shop.goods.length;
      for (var goods of shop.goods) {
        if (check_list.indexOf(goods.goods_id) == -1) {
          goods.check = 0;
        } else {
          goods.check = 1;
          s_num = s_num + parseFloat(goods.goods_total_price);
          s_count = s_count + parseInt(goods.goods_num);
        }
      }
    }
    console.log(check_list, temp);
    if (check_list.length == l && temp.length != 0) {
      that.setData({
        all_check: 1,
      })
    } else {
      that.setData({
        all_check: 0,
      })
    }
    that.setData({
      cart_list: temp,
      cart: {
        num: s_num.toFixed(2),
        cart_count: s_count,
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //添加按钮
  add: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    util.postUrl('cart/cart_add', {
      goods_id: item.goods_id,
      quantity: parseInt(item.goods_num) + 1,
    }, function(res) {
      if (res.data.code == 200) {
        that.initData();
      } else {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none'
        })
        that.setData({
          cart_list: temp,
        })
      }
    })
  },
  del: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    var check_list = that.data.check_list;

    item.goods_num = parseInt(item.goods_num) - 1;
    if (item.goods_num == 0) {
      item.goods_num = 1;
      wx.showModal({
        title: '提示',
        content: '确认要移出购物车？',
        success: function(res) {
          if (res.confirm) {
            util.postUrl('cart/cart_remove', {
              cart_id: item.cart_id,
            }, function(res) {
              if (res) {
                if (check_list.indexOf(item.goods_id) != -1) {
                  check_list.splice(check_list.indexOf(item.goods_id), 1);
                }
                that.setData({
                  check_list: check_list,
                })
                that.initData();
              }

            })
          } else if (res.cancel) {

          }
        }
      })
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.goods_num,
      }, function(res) {
        if (res) {
          that.initData();
        }
      })
    }
  },
  //单选
  check: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    var check_list = that.data.check_list;
    var check_list_sp = check_list.indexOf(item.goods_id);
    if (check_list_sp == -1) {
      check_list.push(item.goods_id);
    } else {
      check_list.splice(check_list_sp, 1);
    }
    that.initCheck();  
  },
  //全选
  checkAll: function(e) {
    var that = this;
    that.setData({
      all_check: !that.data.all_check
    })
    var check_list = [];
    var temp = that.data.cart_list;
    if (that.data.all_check) {
      for (var shop of temp) {
        for (var goods of shop.goods) {
          check_list.push(goods.goods_id);
        }
      }
    }
    console.log('check_list', check_list)
    that.setData({
      check_list: check_list,
    })
    that.initCheck();

  },
  //右上角删除
  icon_delete: function() {
    var that = this;
    var temp = that.data.cart_list;
    var my_check = that.data.check_list;
    if (my_check == '') {
      wx.showToast({
        title: '请选择删除商品！',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '确定删除这些商品?',
      success: function(res) {
        if (res.confirm) {
          var check_list = [];
          var temp_list = [];
          for (let shop of temp) {
            for (let goods of shop.goods) {
              if (my_check.indexOf(goods.goods_id) == -1) {
                temp_list.push(goods.goods_id);
              } else {
                check_list.push(goods.cart_id);
              }
            }
          }

          util.postUrl("cart/cart_remove", {
            cart_id: check_list.join(',')
          }, function(res) {
            if (res.data.code == 200) {
              that.setData({
                check_list: temp_list,
              })
              that.initData();
            }
          })
        }
      }
    })



  },
  initRed: function() {
    var that = this;
    util.postUrl('cart/cart_count', {}, function(res) {
      if (res.data.code == 200) {

        if (res.data.datas.count.goods_total_num == 0) {
          that.setData({
            hasGoods: false
          })
          wx.hideTabBarRedDot({
            index: 2,
          })
        } else {
          wx.setTabBarBadge({
            index: 2,
            text: (res.data.datas.count.goods_total_num + ""),
          })
          that.setData({
            hasGoods: true
          })
        }
      }
    })
  },

  /* 输入框事件 */
  bindManual: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        item.quantity = item.num;
        item.goods_num = item.num;
        temp_goods.push(item);
      }

      wx.setStorageSync('temp_goods', temp_goods);
      console.log('temp_goods', wx.getStorageSync('temp_goods'));
      that.initData();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function(res) {
        if (res.data.code == 200) {
          that.initData();
        } else {
          console.log(temp);
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
          that.setData({
            cart_list: temp,
          })
        }

      })
    }

  },
  goSureOrder: function() {
    var that = this;
    var list = this.data.cart_list;
    var check_list = this.data.check_list;

    if (check_list.length == 0) {
      return;
    }

    var order_check = [];
    var cart_id = [];
    for (let shop of list) {
      for (let goods of shop.goods) {
        if (check_list.indexOf(goods.goods_id) != -1) {
          cart_id.push(goods.cart_id + "|" + goods.goods_num);
          order_check.push(goods.goods_id);
        }
      }
    }

    wx.setStorageSync("order_check", order_check);
    wx.navigateTo({
      url: '../sure_order/sure_order?cart_id=' + cart_id.join(","),
    })
  },
  goGoodsDetail: function(e) {
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../goods-details/goods-details?item=' + JSON.stringify(item),
    })
  },
  goClass: function() {
    wx.switchTab({
      url: '../classify/classify',
    })
  },
  goStore:function(e){
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../shop_detail/shop_detail?store_id=' + item.store_id,
    })
  }
})